<template>
  <div class="ai-assistant-container">
    <!-- 圆形悬浮按钮 -->
    <div
        class="floating-button"
        :class="{ 'active': isOpen, 'has-unread': unreadCount > 0 }"
        @click="toggleChat"
    >
      <svg v-if="!isOpen" width="24" height="24" viewBox="0 0 24 24">
        <path fill="currentColor" d="M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2z M12,20c-4.41,0-8-3.59-8-8s3.59-8,8-8s8,3.59,8,8S16.41,20,12,20z M12,11c-0.55,0-1-0.45-1-1V8c0-0.55,0.45-1,1-1s1,0.45,1,1v2C13,10.55,12.55,11,12,11z M12,15c-0.55,0-1-0.45-1-1v-2c0-0.55,0.45-1,1-1s1,0.45,1,1v2C13,14.55,12.55,15,12,15z"/>
      </svg>
      <svg v-else width="24" height="24" viewBox="0 0 24 24">
        <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
      </svg>
      <span v-if="unreadCount > 0" class="unread-badge">
        {{ unreadCount > 9 ? '9+' : unreadCount }}
      </span>
    </div>

    <!-- 聊天对话框 -->
    <transition name="fade">
      <div v-show="isOpen" class="chat-dialog">
        <div class="chat-header">
          <div class="header-content">
            <div class="ai-avatar">
              <svg width="24" height="24" viewBox="0 0 24 24">
                <path fill="currentColor" d="M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M7.07,18.28C7.5,17.38 10.12,16.5 12,16.5C13.88,16.5 16.5,17.38 16.93,18.28C15.57,19.36 13.86,20 12,20C10.14,20 8.43,19.36 7.07,18.28M18.36,16.83C16.93,15.09 13.46,14.5 12,14.5C10.54,14.5 7.07,15.09 5.64,16.83C4.62,15.5 4,13.82 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,13.82 19.38,15.5 18.36,16.83M12,6C10.06,6 8.5,7.56 8.5,9.5C8.5,11.44 10.06,13 12,13C13.94,13 15.5,11.44 15.5,9.5C15.5,7.56 13.94,6 12,6M12,11A1.5,1.5 0 0,1 10.5,9.5A1.5,1.5 0 0,1 12,8A1.5,1.5 0 0,1 13.5,9.5A1.5,1.5 0 0,1 12,11Z"/>
              </svg>
            </div>
            <h3>AI 助手</h3>
          </div>
          <button class="close-btn" @click="isOpen = false">
            <svg width="16" height="16" viewBox="0 0 24 24">
              <path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"/>
            </svg>
          </button>
        </div>
        <div class="chat-content" ref="chatContent">
          <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
            <div class="message-content" v-html="formatMessage(msg.content)"></div>
          </div>
          <div v-if="loading" class="loading">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
        <div class="chat-input">
          <div class="input-container">
            <input
                v-model="userInput"
                @keyup.enter="sendMessage"
                placeholder="输入您的问题..."
                :disabled="loading"
            />
            <button
                @click="sendMessage"
                :disabled="loading || !userInput.trim()"
                class="send-button"
            >
              <svg width="20" height="20" viewBox="0 0 24 24">
                <path fill="currentColor" d="M2,21L23,12L2,3V10L17,12L2,14V21Z"/>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import deepseekApi from '@/api/deepseek';

export default {
  data() {
    return {
      isOpen: false,
      messages: [],
      userInput: '',
      loading: false,
      unreadCount: 0,
      lastSeenIndex: -1
    };
  },
  watch: {
    messages: {
      deep: true,
      handler() {
        this.updateUnreadCount();
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    isOpen(newVal) {
      if (newVal) {
        this.unreadCount = 0;
        this.lastSeenIndex = this.messages.length - 1;
      }
    }
  },
  async created() {
    try {
      const response = await fetch('/db.sql');
      if (!response.ok) {
        throw new Error('无法读取SQL文件');
      }
      const sqlContent = await response.text();
      this.messages.push({
        role: 'user',
        content: `以下是SQL文件内容：${sqlContent}，请记住这些内容以便后续回答问题。`
      });
      this.loading = true;
      const responseFromAI = await deepseekApi.chatCompletion(this.messages);
      this.messages.push({
        role: 'assistant',
        content: responseFromAI.choices[0].message.content
      });
      this.loading = false;
    } catch (error) {
      console.error('读取SQL文件时出错:', error);
      this.messages.push({
        role: 'assistant',
        content: '抱歉，无法读取SQL文件。'
      });
    }
  },
  methods: {
    toggleChat() {
      this.isOpen = !this.isOpen;
      if (this.isOpen) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    updateUnreadCount() {
      if (!this.isOpen) {
        this.unreadCount = Math.max(0, this.messages.length - 1 - this.lastSeenIndex);
      } else {
        this.unreadCount = 0;
        this.lastSeenIndex = this.messages.length - 1;
      }
    },
    async sendMessage() {
      if (!this.userInput.trim() || this.loading) return;

      const userMessage = this.userInput;
      this.messages.push({role: 'user', content: userMessage});
      this.userInput = '';
      this.loading = true;

      try {
        const response = await deepseekApi.chatCompletion(this.messages);
        this.messages.push({
          role: 'assistant',
          content: response.choices[0].message.content
        });
      } catch (error) {
        this.messages.push({
          role: 'assistant',
          content: '抱歉，AI服务暂时不可用'
        });
      } finally {
        this.loading = false;
        this.scrollToBottom();
      }
    },
    scrollToBottom() {
      const container = this.$el.querySelector('.chat-content');
      container.scrollTop = container.scrollHeight;
    },
    formatMessage(content) {
      // 格式化代码块
      content = content.replace(/```(\w*)([\s\S]*?)```/g, '<pre><code>$2</code></pre>');

      // 格式化行内代码
      content = content.replace(/`([^`]+)`/g, '<code>$1</code>');

      // 格式化链接
      content = content.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');

      // 格式化粗体
      content = content.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');

      // 格式化斜体
      content = content.replace(/\*([^*]+)\*/g, '<em>$1</em>');

      // 格式化列表
      content = content.replace(/^\s*-\s(.+)/gm, '<li>$1</li>');
      content = content.replace(/(<li>.*<\/li>)/g, '<ul>$1</ul>');

      // 保留换行符
      content = content.replace(/\n/g, '<br>');

      return content;
    }
  }
};
</script>

<style scoped>
.ai-assistant-container {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 1000;
  font-family: 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.floating-button {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #4a6fa5;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  position: relative;
}

.floating-button:hover {
  background-color: #3a5a80;
  transform: scale(1.1);
}

.floating-button.active {
  background-color: #ff4757;
}

.floating-button.has-unread::after {
  content: '';
  position: absolute;
  top: -3px;
  right: -3px;
  width: 12px;
  height: 12px;
  background-color: #ff4757;
  border-radius: 50%;
  border: 2px solid #fff;
}

.unread-badge {
  position: absolute;
  top: -6px;
  right: -6px;
  background-color: #ff4757;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: bold;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.chat-dialog {
  position: absolute;
  bottom: 80px;
  right: 0;
  width: 380px;
  max-height: 500px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: 1px solid #e1e1e1;
}

.chat-header {
  padding: 16px;
  background: linear-gradient(135deg, #4a6fa5 0%, #3a5a80 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.ai-avatar {
  width: 32px;
  height: 32px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.chat-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  max-height: 400px;
  background-color: #f9f9f9;
  scroll-behavior: smooth;
}

.message {
  margin-bottom: 16px;
  max-width: 85%;
  word-wrap: break-word;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message.user {
  margin-left: auto;
  background-color: #4a6fa5;
  color: white;
  border-radius: 18px 18px 4px 18px;
  padding: 12px 16px;
}

.message.assistant {
  margin-right: auto;
  background-color: #ffffff;
  color: #333;
  border-radius: 18px 18px 18px 4px;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.message-content {
  line-height: 1.5;
}

.message-content >>> pre {
  background-color: #f5f5f5;
  border-radius: 6px;
  padding: 12px;
  overflow-x: auto;
  margin: 8px 0;
  font-family: 'Courier New', monospace;
  font-size: 14px;
}


.message-content >>> code {
  background-color: #f5f5f5;
  padding: 2px 4px;
  border-radius: 4px;
  color: black;
  font-family: 'Courier New', monospace;
  font-size: 14px;
}

.message-content >>> a {
  color: #4a6fa5;
  text-decoration: none;
  font-weight: 500;
}

.message-content >>> a:hover {
  text-decoration: underline;
}

.message-content >>> strong {
  font-weight: 600;
}

.message-content >>> em {
  font-style: italic;
}

.message-content >>> ul {
  padding-left: 20px;
  margin: 8px 0;
}

.message-content >>> li {
  margin-bottom: 4px;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 12px;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #4a6fa5;
  border-radius: 50%;
  display: inline-block;
  animation: bounce 1.4s infinite ease-in-out both;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.chat-input {
  padding: 12px 16px;
  border-top: 1px solid #e1e1e1;
  background-color: #fff;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chat-input input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 24px;
  outline: none;
  font-size: 14px;
  transition: border-color 0.2s;
}

.chat-input input:focus {
  border-color: #4a6fa5;
}

.send-button {
  width: 40px;
  height: 40px;
  background-color: #4a6fa5;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.send-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.send-button:hover:not(:disabled) {
  background-color: #3a5a80;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>